package zhieasy.cn.service.course.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import zhieasy.cn.common.form.GetCourseForm;
import zhieasy.cn.common.utils.CmdScriptUtils;
import zhieasy.cn.service.common.impl.CommonInitServiceImpl;
import zhieasy.cn.service.common.script.AuthCodeSession;
import zhieasy.cn.service.course.GetCourseService;
import zhieasy.cn.service.course.script.CourseInfoRequest;
import zhieasy.cn.service.course.script.CourseScriptData;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 学生课表服务
 * @author zouchanglin
 */
@Slf4j
@Service
public class GetCourseServiceImpl implements GetCourseService {
    @Resource
    private CommonInitServiceImpl commonInitService;

    @Override
    public String getAuthCodeImage(String openId) {
        return commonInitService.getAuthCodeImage(openId);
    }

    @Override
    public List<CourseScriptData> getCourseInfo(GetCourseForm getCourseForm, String wxOpenId) {
        AuthCodeSession authCodeSession = CommonInitServiceImpl.weChatSessionCache.get(wxOpenId);
        AuthCodeSession.Data authCodeSessionData = authCodeSession.getData();
        CourseInfoRequest courseRequest = new CourseInfoRequest(
                getCourseForm.getAuthCode(),
                getCourseForm.getStudentId(),
                getCourseForm.getPassword(),
                getCourseForm.getSchoolYear(),
                getCourseForm.getTerm(),
                authCodeSessionData.getLocation_url(),
                authCodeSessionData.getHave_location_url()
        );

        String[] cmd = {"python", CommonInitServiceImpl.courseInfoScript.getAbsolutePath(), JSON.toJSONString(courseRequest)};
        String result = CmdScriptUtils.execCmd(cmd);
        String dataStr = JSON.parseObject(result).getString("data");
        log.info("dataStr = {}", dataStr);

        String error = JSON.parseObject(result).getString("error");
        log.info("errorCode = {}", error);

        if("0".equals(error)){
            CommonInitServiceImpl.weChatSessionCache.remove(wxOpenId);
            List<CourseScriptData> courseData = JSON.parseArray(JSON.parseObject(dataStr).getString("course_info"), CourseScriptData.class);
            for(CourseScriptData data: courseData){
                log.info("CourseScriptData = {}", data.toString());
            }
            return courseData;
        }
        return new ArrayList<>();
    }
}
